# time:2019/7/26
# text:第一个接口
import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator

from django.views import View
from django.views.decorators.csrf import csrf_exempt

# ftv@csrf_exempt是免除csrf认证
from rest_framework.authentication import BaseAuthentication
from rest_framework.views import APIView

from apps import models


#
# @csrf_exempt
# def user(request):
#     user_list = ['a', 'b']
#     return HttpResponse(json.dumps(user_list))
#
#
# from django.utils.decorators import method_decorator
#
#
# # method_decorator是ctv免除csrf认证的
# @method_decorator(csrf_exempt, name='dispatch')
# class demo(View):
#     def get(self, request, *args, **kwargs):
#         return HttpResponse('Get')
#
#     def post(self, request, *args, **kwargs):
#         return HttpResponse('Post')

#
# @method_decorator(csrf_exempt, name='dispatch')
# class order(APIView):
#     # authentication_classes = [BaseAuthentication,]
#     def get(self, request, *args, **kwargs):
#
#         # self.dispatch
#         print("请求发那个是",request)
#         casa = {"id": 1, "case_name": "开发"}
#         return HttpResponse(json.dumps(casa), status=200)
#
#     def post(self, request, *args, **kwargs):
#         return HttpResponse('新增订单')
#
#     def put(self, request, *args, **kwargs):
#         return HttpResponse('更新订单')
#
#     def delete(self, request, *args, **kwargs):
#         return HttpResponse('删除订单')
# @method_decorator(csrf_exempt, name='dispatch')
def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding="utf-8"))
    return m.hexdigest()


class AuthView(APIView):
    # authentication_classes = [BaseAuthentication,]

    def get(self, request, *args, **kwargs):
        # self.dispatch
        # print("请求发那个是", request)
        token = request.data.get('token')
        # obj = models.UserToken.objects.filter(token=token).first()
        obj = models.UserToken.objects.filter(token=token)
        ret = {'code': 1000, 'msg': "查询成功"}

        try:
            if token == None:
                ret['code'] = 1002
                ret['msg'] = "token不能为空"
            elif not obj:
                ret['code'] = 1003
                ret['msg'] = "token错误"
            else:
                names = obj.get().user.username
                pw = obj.get().user.password
                ret['user'] = names
                ret['password'] = pw

        except Exception as e:

            ret['code'] = 1004
            ret['msg'] = "请求异常"
        return JsonResponse(ret)

    def post(self, request, *args, **kwargs):
        ret = {'code': 100, 'msg': "登录成功"}
        try:
            # 2 application/json 获取
            # getlist返回的是列表
            # user1 = request.data.getlist('uesrname')
            # usernames = ['zhangning', 'hello'] (list)
            user = request.data.get('uesrname')
            pwd = request.data.get('password')
            obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
            # obj2 = models.UserInfo.objects.filter(username=user, password=pwd)
            if not obj:
                ret['code'] = 1001
                ret['msg'] = "用户名或者密码错位"
            token = md5(user)
            # 存在就更新，不存在就创建
            print("-------------", token)
            models.UserToken.objects.update_or_create(user=obj, defaults={'token': token})
            ret['tonken'] = token
        except Exception as e:
            ret['code'] = 1002
            ret['msg'] = "请求异常"
        return JsonResponse(ret)

    def put(self, request, *args, **kwargs):
        return HttpResponse('更新订单')

    def delete(self, request, *args, **kwargs):
        return HttpResponse('删除订单')
